<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./css/message.css">
  <link rel="stylesheet" href="./vender/calendar-selector.css">
</head>

<body>
  <div class="page-container">
    <div class="flex py-2">
      <select id="chat-object" class="flex-1"></select>
      <select id="chat-profile" class="flex-1"></select>
    </div>
    <div class="chat-content-area">
      <div class="section-title flex">
        <div>聊天内容</div>
        <div class="ml-auto">
          <div class="chat-create">对话生成</div>
        </div>
        <div class="clear-records">清空记录</div>
      </div>
      <div class="chat-textarea">
        <div id="chat-content"></div>
      </div>
    </div>
    <div class="chat-footer">
      <select id="current-sender">设置发送方</select>
      <div class="flex  my-2">
        <select id="chat-type">消息</select>
        <div class="chat-input-outer">
          <input class="chat-input" type="text" />
        </div>
        <button class="btn-confirm">发送</button>
      </div>
      <button class="btn-submit">查看效果</button>
    </div>
  </div>
</body>
<script src="./utils/dropdown.js"></script>
<script src="./vender/calendar-selector.js"></script>
<script>
  let datePickerInstance = null
  const renderChatContent = () => {
    const chatObject = JSON.parse(localStorage.getItem('chat-object'))
    const chatProfile = JSON.parse(localStorage.getItem('chat-profile'))
    const chatType = JSON.parse(localStorage.getItem('chat-type'))
    const chatContent = JSON.parse(localStorage.getItem('chat-content') || "[]")
    //[{role:a||b,type:"1||2||3||4",time:"",content:""}]
    document.querySelector('#chat-content').innerHTML = `
      ${chatContent.map(v => {
      if (v.type !== "time") {
        let currentName = ""
        if (v.role === "sender") {
          currentName = chatProfile.label
        } else {
          currentName = chatObject.label
        }
        return `<div>
          <span style="color:${v.role === "sender" ? "green" : "red"}">${currentName}：</span>
          <span >${v.type === "phone" ? `发起通话，时长:${v.content}` : v.content}</span>
        </div>`
      } else {
        return `<div style="text-align:center">
          -----------<span >${v.content}</span>-----------
        </div>`
      }
    }).join('')}
    `
  }
  const setSelectOption = (selector, list, key) => {
    document.querySelector(selector).innerHTML = `
      ${list.map((v) => {
      return `<option value=${JSON.stringify(v)}>${v.label}</option>`
    }).join("")}
    `;
    document.querySelector(selector).addEventListener("change", function (event) {
      localStorage.setItem(key, event.target.value)
      if (key === "chat-type") {
        const curType = JSON.parse(localStorage.getItem(key))
        if (curType?.value === "time") {
          datePickerInstance = document.querySelector('.chat-input').flatpickr({
            enableTime: true,
            // 如果你希望用户选择具体的时间，你可以使用以下选项
            noCalendar: false,
          });
        } else if (curType?.value === "phone") {
          datePickerInstance = document.querySelector('.chat-input').flatpickr({
            enableTime: true, // 启用时间选择
            noCalendar: true, // 禁用日期选择
            altInput: true, // 使用备用输入字段来显示选择的值
            altFormat: "H:i", // 设置备用输入字段的时间格式
            dateFormat: "H:i", // 设置日期格式（这个不会显示出来，只是为了满足Flatpickr的要求）
          });
        } else {
          datePickerInstance?.destroy();
        }
      }
    });
    document.querySelector(selector).value = localStorage.getItem(key)
    if (key === "chat-type") {
      const curType = JSON.parse(localStorage.getItem(key))
      if (curType?.value === "time") {
        datePickerInstance = document.querySelector('.chat-input').flatpickr({
          enableTime: true,
          // 如果你希望用户选择具体的时间，你可以使用以下选项
          noCalendar: false,
        });
      } else if (curType?.value === "phone") {
        datePickerInstance = document.querySelector('.chat-input').flatpickr({
          enableTime: true, // 启用时间选择
          noCalendar: true, // 禁用日期选择
          altInput: true, // 使用备用输入字段来显示选择的值
          altFormat: "H:i", // 设置备用输入字段的时间格式
          dateFormat: "H:i", // 设置日期格式（这个不会显示出来，只是为了满足Flatpickr的要求）
        });
      } else {
        datePickerInstance?.destroy();
      }
    }
  }
</script>
<script>
  document.querySelector('.clear-records').addEventListener("pointerdown", () => {
    localStorage.removeItem('chat-content')
    renderChatContent()
  })
</script>
<script>
  const targetEle = document.querySelector("#chat-object")
  const profileEle = document.querySelector("#chat-profile")
  const typeEle = document.querySelector("#chat-type")
  const senderEle = document.querySelector("#current-sender")

  document.addEventListener("contextmenu", (e) => {
    e.preventDefault()
    $dropdown.hidden()
  })
  document.querySelector('.btn-submit').addEventListener("pointerdown", () => {
    window.location.href = "./index.html"
  })
  document.querySelector('.btn-confirm').addEventListener("pointerdown", () => {
    const contentList = JSON.parse(localStorage.getItem("chat-content") || "[]")
    const chatObject = JSON.parse(localStorage.getItem('chat-object'))
    const chatProfile = JSON.parse(localStorage.getItem('chat-profile'))
    const chatType = JSON.parse(localStorage.getItem('chat-type'))
    const sender = JSON.parse(localStorage.getItem('sender'))
    const currentMsg = document.querySelector(".chat-input").value
    const msgObject = {
      role: sender.value,
      type: chatType.value,
      content: currentMsg,
      time: currentMsg
    }
    contentList.push(msgObject)
    if (currentMsg.length > 0) {
      localStorage.setItem("chat-content", JSON.stringify(contentList))
      document.querySelector(".chat-input").value = ""
      renderChatContent()
    }
  })


</script>
<script>
  window.onload = () => {
    const chatObject = JSON.parse(localStorage.getItem('chat-object'))
    const chatProfile = JSON.parse(localStorage.getItem('chat-profile'))
    const chatType = JSON.parse(localStorage.getItem('chat-type'))
    const sender = JSON.parse(localStorage.getItem('sender'))
    // if (chatType.id === "3") {
    //   datePickerInstance = document.querySelector('.chat-input').flatpickr({
    //     enableTime: true,
    //     // 如果你希望用户选择具体的时间，你可以使用以下选项
    //     noCalendar: false,
    //   });
    // }
    renderChatContent()
    setSelectOption("#chat-object", [
      { id: "1", value: "zhangzhiming", label: "张智铭" },
      { id: "2", value: "zhangzhiyong", label: "张志勇" }
    ], 'chat-object')
    setSelectOption("#chat-profile", [
      { id: "1", value: "gaojiale", label: "高佳乐", tel: "173****1286" },
      { id: "2", value: "chenmiao", label: "陈苗", tel: "183****8762" }
    ], 'chat-profile')
    setSelectOption("#chat-type", [
      { id: "1", value: "message", label: "消息" },
      { id: "2", value: "phone", label: "通话" },
      { id: "3", value: "time", label: "时间" },
    ], 'chat-type')
    setSelectOption("#current-sender", [
      { id: "1", value: "sender", label: "发送方" },
      { id: "2", value: "receiver", label: "接收方" }
    ], 'sender')
  }
</script>
<script>
  //生成对话
  document.querySelector(".chat-create").addEventListener("pointerdown", () => {
    console.log('对话生成')

    const tableContent = prompt('输入表格数据：', ``)
    if (tableContent) {
      let content = tableContent.trim()
      const contentList = content.split('\n')
      const zyRecord = []
      const zmRecord = []
      contentList.forEach(c => {
        const arr = c.split('\t')
        if (arr[1] === "张志勇") {
          zyRecord.push({
            content: arr[0],
            role: "sender",
            time: arr[0],
            type: "time"
          })
          zyRecord.push({
            content: arr[2],
            role: "sender",
            time: arr[2],
            type: "phone"
          })
        } else {
          zmRecord.push({
            content: arr[0],
            role: "sender",
            time: arr[0],
            type: "time"
          })
          zmRecord.push({
            content: arr[2],
            role: "sender",
            time: arr[2],
            type: "phone"
          })
        }
      })
      const chatObject = JSON.parse(localStorage.getItem('chat-object'))
      if (chatObject.value === 'zhangzhiyong') {
        localStorage.setItem("chat-content", JSON.stringify(zyRecord))
      } else if (chatObject.value === 'zhangzhiming') {
        localStorage.setItem("chat-content", JSON.stringify(zmRecord))
      }
      renderChatContent()
    }
    //形式 先是时间，再试通话，消息不重要   
    //对应生成五天的对话，设置第一段对话时间，控制电话时间段在上班时间内，通话时长，大概在1-10min
  })
</script>

</html>